﻿using log4net;
using Lottery.Data;
using Lottery.Model;
using System;
using System.Media;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;



namespace Lottery
{
    public partial class MainWindow : Window
    {
        #region 字段
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private DispatcherTimer timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 10) };
        private DispatcherTimer showtimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 1, 0) };
        private Label labLevel = null;
        private Label labGift = null;
        private Label[] labels = null;
        private GiftInfo nowGift = null;
        private StaffInfo nowStaff = null;
        private SoundPlayer sound = null;
        private SoundPlayer sound2 = null;
        //private SocketHepler server = new SocketHepler();

        //0:未开始，
        public enum RunSate { Start, Stop, Over };

        private RunSate runSate = RunSate.Stop;




        #endregion

        public MainWindow()
        {
            timer.Tick += new EventHandler(timer_Tick);
            showtimer.Tick += new EventHandler(showtimer_Tick);
            InitializeComponent();
            try
            {
                //读取设置
                this.loadConfig();
                //读取背景图
                this.loadBgImage();
                //设置布局
                this.layout();
                //读取声音
                this.loadSound();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Current.Shutdown();
            }
        }

        /// <summary>
        /// 配置初始化，遇到问题强制退出
        /// </summary>
        private void loadConfig()
        {
            this.Title = MyConfig.Instance.AppTitle;
            this.moveTextBlock.Text = MyConfig.Instance.MessageBar;
        }

        /// <summary>
        /// 声音初始化
        /// </summary>
        private void loadSound()
        {
            // sound = new SoundPlayer(MyResources.GetSoundsPath("gu.wav"));
            // sound2 = new SoundPlayer(MyResources.GetSoundsPath("peng.wav"));
            sound = new SoundPlayer(MyResources.GetSoundsPath("start.wav"));
            sound2 = new SoundPlayer(MyResources.GetSoundsPath("end.wav"));
            this.bgMediaElement.Source = new Uri(MyResources.GetSoundsPath(MyConfig.Instance.SoundQueue.Dequeue()));
            this.bgMediaElement.Play();
        }

        /// <summary>
        /// 图像初始化
        /// </summary>
        /// <param name="fileName"></param>
        private void loadBgImage()
        {
            String fileName = "bg.jpg";
            this.Background = MyResources.GetImageBrush(fileName);
            int mywidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; //屏幕宽度 
            int myheight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; //屏幕高度
            System.Drawing.Image image = MyResources.GetImage(fileName);
            this.Width = image.Width > mywidth ? mywidth : image.Width;
            this.Height = image.Height > myheight ? myheight : image.Height;
        }

        private void layout()
        {
            this.Cursor = System.Windows.Input.Cursors.None;
            //this.btnCheck.Margin = new Thickness((this.Width - btnCheck.Width) / 2 + 100, 0, (this.Width - btnCheck.Width) / 2 - 10, 100);

            //去掉按钮
            //this.btnCheck.Focus();
            this.labGift = this.getOneLable("labGift");
            //this.labGift.Content = "礼品";
            this.getTitleLable(labGift);

            this.labGift.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            this.labLevel = this.getOneLable("labLevel");
            //this.labLevel.Content = "等级";
            this.labLevel.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            this.getTitleLable(labLevel);
            MainGrid.Children.Add(labGift);
            MainGrid.Children.Add(labLevel);
            //weihangl,2015-12-04
            //this.labGift.Margin = new Thickness(0, this.Height * 0.35, 0, 0);//0.3,此处修改抽奖奖品在全屏幕的高度
            //this.labLevel.Margin = new Thickness(0, this.Height * 0.45, 0, 0);//0.4,此处修改抽奖奖品等级在全屏幕的高度
            this.labGift.Margin = new Thickness(0, this.Height * 0.3, 0, 0);//0.3,此处修改抽奖奖品在全屏幕的高度，用于笔记本的分辨率1366*768
            this.labLevel.Margin = new Thickness(0, this.Height * 0.4, 0, 0);//0.4,此处修改抽奖奖品等级在全屏幕的高度，用于笔记本的分辨率
                                                                             //this.button1.Width = this.Width * 0.2;
                                                                             //this.button1.Height = this.Height * 0.1;

            //this.labGift.Background = MyResources.GetImageBrush("gift-bg.jpg");
            //this.labLevel.Background = MyResources.GetImageBrush("gift-bg.jpg");
        }

        /// <summary>
        /// 得到标题Lable
        /// </summary>
        /// <param name="lable"></param>
        /// <returns></returns>
        private Label getTitleLable(Label lable)
        {
            lable.FontFamily = new FontFamily("STXingkai");
            lable.FontSize = 60;
            lable.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("yellow"));
            return lable;
        }


        /// <summary>
        /// 点击抽奖按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lottery()
        {


            this.nowGift = GiftData.Instances.RandomGift;
            if (nowGift == null)
            {
                MessageBox.Show("没有奖品了", "抽奖提示", MessageBoxButton.OK, MessageBoxImage.Information);
                this.runSate = RunSate.Over;
                return;
            }
            this.nowStaff = StaffData.Instances.RandomStaff();
            if (nowStaff == null)
            {
                MessageBox.Show("没有参与者了", "抽奖提示", MessageBoxButton.OK, MessageBoxImage.Information);
                this.runSate = RunSate.Over;
                return;
            }

            switch (runSate)
            {
                //如果是停滞状态就启动抽奖
                case RunSate.Stop:
                    this.runSate = RunSate.Start;

                    this.bgMediaElement.Pause();
                    sound.PlayLooping();
                    this.labLevel.Content = "    " + nowGift.LevelName + "    ";
                    this.labGift.Content = "    " + nowGift.Name + "    ";
                    timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
                    timer.IsEnabled = true;


                    break;
                //如果是开启状态就开启抽奖
                case RunSate.Start:
                    this.runSate = RunSate.Stop;

                    this.bgMediaElement.Play();
                    sound.Stop();
                    sound2.Play();

                    if (timer.Interval == new TimeSpan(0, 0, 0, 0, 10))
                        timer.Interval = new TimeSpan(0, 0, 0, 0, 50);
                    this.timer.Interval += new TimeSpan(0, 0, 0, 0, 20);
                    break;
                default:
                    MessageBox.Show("没有参与者或者奖品了", "抽奖提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    break;

            }



        }

        /// <summary>
        /// 时钟控制数字跳动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            this.nowStaff = StaffData.Instances.RandomStaff();
            if (nowStaff == null)
            {
                return;
            }
            String jobno = this.nowStaff.JobNo;
            if (this.timer.Interval >= new TimeSpan(0, 0, 0, 0, 200))
            {
                //进入中奖状态
                this.nowStaff = StaffData.Instances.RandomStaff(this.nowGift);
                jobno = this.nowStaff.JobNo;
                this.timer.IsEnabled = false;
                this.showJobNo(jobno);
                showtimer.Start();
                return;
            }
            else if (this.timer.Interval > new TimeSpan(0, 0, 0, 0, 10) && this.timer.Interval < new TimeSpan(0, 0, 0, 0, 200))
            {
                this.timer.Interval += new TimeSpan(0, 0, 0, 0, 20);
            }
            this.showJobNo(jobno);
        }

        /// <summary>
        /// 延迟跳出中奖窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void showtimer_Tick(object sender, EventArgs e)
        {
            this.showtimer.Stop();
            this.win();
        }

        /// <summary>
        /// 滚动结束，获奖者信息
        /// </summary>
        private void win()
        {

            WinnerInfo winner = WinnerData.Instances.GoToWin(this.nowStaff, this.nowGift);
            this.moveTextBlock.Text = string.Format("祝贺[{0}]{1}获得[{2}]{3}一{4}。", winner.JobNo, winner.StaffName, winner.GiftLevelName, winner.GiftName, winner.GiftUnit);
            new WinWindow(winner).Show();


        }

        /// <summary>
        /// 显示滚动的数字效果
        /// </summary>
        /// <param name="jobno"></param>
        private void showJobNo(String jobno)
        {
            char[] cs = jobno.ToCharArray();
            if (this.labels == null || this.labels.Length != jobno.Length)
            {
                if (this.labels != null)
                {
                    foreach (Label l in this.labels)
                    {
                        MainGrid.Children.Remove(l);
                    }
                }
                this.labels = new Label[jobno.Length];
                ImageBrush image = new ImageBrush();
                image.ImageSource = new BitmapImage(new Uri(@"Images\number.gif", UriKind.Relative));
                for (int i = 0; i < labels.Length; i++)
                {
                    Label l = this.getOneLable("numlable" + i);
                    l.Width = 70;
                    l.Height = 90;
                    l.Background = image;
                    l.FontSize = 60;
                    l.Content = cs[i];
                    double al = (jobno.Length * l.Width + (jobno.Length - 1) * 10);
                    double w = this.Width / 2 - al / 2 + i * (l.Width + 10) - 5;
                    //weihangl,2015-12-04
                    //l.Margin = new Thickness(w, this.Height / 1.75, w - i * (l.Width + 10) * 2, 0);//此处修改跳动数字的位置
                    l.Margin = new Thickness(w, this.Height / 2, w - i * (l.Width + 10) * 2, 0);//此处修改跳动数字的位置，用于笔记本的分辨率
                    this.labels[i] = l;
                    MainGrid.Children.Add(l);
                }
            }
            else
            {
                for (int i = 0; i < labels.Length; i++)
                {
                    this.labels[i].Content = cs[i];
                }
            }
        }

        /// <summary>
        /// 得到一个标准的lable
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private Label getOneLable(String name)
        {
            Label l = new Label();
            l.FontFamily = new FontFamily("Impact");
            l.FontWeight = FontWeights.Black;
            l.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            l.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            l.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
            l.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
            return l;
        }

        /// <summary>
        /// 双击最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.WindowState != System.Windows.WindowState.Maximized)
                this.WindowState = System.Windows.WindowState.Maximized;
            else
                this.WindowState = System.Windows.WindowState.Normal;
        }

        /// <summary>
        /// 滚轮控制音量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainGrid_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                this.bgMediaElement.Volume += 0.1;
                if (this.bgMediaElement.Volume > 1)
                {
                    AutoSound.VolumeUp();
                    this.bgMediaElement.Volume = 1;
                }
            }
            else
            {
                if (this.bgMediaElement.Volume <= 1 && this.bgMediaElement.Volume > 0)
                {
                    this.bgMediaElement.Volume -= 0.05;
                    AutoSound.VolumeDown();
                }
                if (this.bgMediaElement.Volume < 0)
                {
                    this.bgMediaElement.Volume = 0;
                }
            }
        }

        /// <summary>
        /// 播放完之后自动下一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            this.bgMediaElement.Source = new Uri(MyResources.GetSoundsPath(MyConfig.Instance.SoundQueue.Dequeue()));
        }

 

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Space || e.Key == System.Windows.Input.Key.Down || e.Key == System.Windows.Input.Key.Enter)
            {
                this.lottery();
            }
            else if (e.Key == System.Windows.Input.Key.F12)
            {
                ConfigWindows configWindows = new ConfigWindows();
                configWindows.ShowDialog();

            }
            else if (e.Key == System.Windows.Input.Key.Escape)
            {
                MessageBoxResult result = MessageBox.Show("是否真的退出？", "退出抽奖", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                if (result.Equals(MessageBoxResult.Yes))
                    this.Close();
            }

            //this.MainGrid.Focus();
        }
    }
}
